import React, { type CSSProperties, useCallback, useRef, useState } from 'react';
import Logo from '../../../components/Logo';
import './Empty.css';
import { ActionIcon, Button, TextArea, Tooltip } from '@lobehub/ui';
import { Paperclip, Globe, X, ArrowUp } from 'lucide-react';
import { useWebSearch, useFileSelection, useFileUpload, useAgentsInitialization } from '../../../store/agents/hooks';

// CSS-in-JS 样式定义
const styles: Record<string, CSSProperties> = {
    container: {
        minHeight: '100%',
        background: '#0a0a0a',
        color: 'white',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '2rem',
        position: 'relative',
    },

    logoContainer: {
        marginBottom: '2rem',
        opacity: 0.9,
    },

    welcomeTitle: {
        fontSize: '2rem',
        fontWeight: 600,
        margin: 0,
        marginBottom: '0.5rem',
        textAlign: 'center',
        color: '#ffffff',
    },

    subtitle: {
        fontSize: '1rem',
        margin: 0,
        marginBottom: '3rem',
        color: '#a0a0a0',
        textAlign: 'center',
    },

    inputSection: {
        width: '100%',
        maxWidth: '600px',
    },

    inputContainer: {
        background: 'var(--bg-color)',
        border: '1px solid #333',
        borderRadius: '12px',
        padding: '1rem',
        marginBottom: '0.5rem',
    },

    inputField: {
        width: '100%',
        background: 'transparent',
        border: 'none',
        outline: 'none',
        color: '#fff',
        fontSize: '1rem',
        lineHeight: 1.5,
        resize: 'none' as const,
        fontFamily: 'inherit',
    },

    toolbar: {
        display: 'flex',
        alignItems: 'center',
        gap: '0.5rem',
        marginTop: '0.5rem',
    },

    toolButton: {
        borderRadius: '12px',
        padding: '0.25rem 0.5rem',
        color: '#ccc',
        fontSize: '0.85rem',
        cursor: 'pointer',
        display: 'flex',
        alignItems: 'center',
        gap: '0.25rem',
        transition: 'all 0.2s ease',
    },

    hiddenInput: {
        display: 'none',
    },

    fileStatus: {
        color: '#888',
        fontSize: '0.75rem',
        marginLeft: '0.5rem',
    },

    modelTag: {
        background: 'var(--bg-color)',
        border: '1px solid #666',
        borderRadius: '6px',
        padding: '0.25rem 0.5rem',
        color: '#fff',
        fontSize: '0.85rem',
        marginLeft: 'auto',
    },

    fileList: {
        marginBottom: '0.75rem',
        display: 'flex',
        flexWrap: 'wrap' as const,
        gap: '0.5rem',
    },

    fileCard: {
        background: 'var(--bg-color)',
        border: '1px solid #666',
        borderRadius: '8px',
        padding: '0.5rem',
        display: 'flex',
        alignItems: 'center',
        gap: '0.5rem',
        minWidth: '150px',
        position: 'relative' as const,

        // 动画
        transition: 'all 0.2s ease',
    },

    fileIcon: {
        width: '32px',
        height: '32px',
        borderRadius: '4px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        fontSize: '0.7rem',
        fontWeight: 600,
        textTransform: 'uppercase' as const,
    },

    fileInfo: {
        flex: 1,
        overflow: 'hidden',
    },

    fileName: {
        fontSize: '0.85rem',
        fontWeight: 500,
        marginBottom: '0.1rem',
        whiteSpace: 'nowrap' as const,
        overflow: 'hidden',
        textOverflow: 'ellipsis',
    },

    fileType: {
        color: '#888',
        fontSize: '0.75rem',
    },

    removeButton: {
        position: 'absolute' as const,
        top: '0.25rem',
        right: '0.25rem',
        width: '20px',
        height: '20px',
        background: '#333',
        border: 'none',
        borderRadius: '50%',
        color: '#fff',
        cursor: 'pointer',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        fontSize: '12px',
        transition: 'all 0.2s ease',
    },

    removeButtonHover: {
        background: '#555',
    }
};

export default function Empty() {
    // 使用agents hooks
    const { webSearchEnabled, toggleWebSearch } = useWebSearch();
    const { selectedFiles, handleFileRemove } = useFileSelection();
    const { handleFileUpload } = useFileUpload();
    const [isLoading, setIsLoading] = useState(false);
    const [value, setValue] = useState('');

    // 初始化agents设置
    useAgentsInitialization();

    // 文件选择ref
    const fileInputRef = useRef<HTMLInputElement>(null);

    // 处理文件选择按钮点击
    const handlePaperclipClick = useCallback(() => {
        fileInputRef.current?.click();
    }, []);

    // 处理文件选择
    const handleFileChange = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (files && files.length > 0) {
            await handleFileUpload(files);
        }
        // 清空input value以允许重新选择相同文件
        if (event.target) {
            event.target.value = '';
        }
    }, [handleFileUpload]);

    // 处理联网搜索切换
    const handleGlobeClick = useCallback(() => {
        toggleWebSearch();
    }, [toggleWebSearch]);

    // 处理文件删除
    const handleRemoveFile = useCallback((fileId: string) => {
        handleFileRemove(fileId);
    }, [handleFileRemove]);

    // 获取文件类型显示
    const getFileTypeDisplay = useCallback((fileName: string, fileType: string) => {
        const extension = fileName.split('.').pop()?.toLowerCase();
        return extension || fileType || 'file';
    }, []);

    // 处理发送按钮点击
    const handleSendClick = useCallback(async () => {
        setIsLoading(true);

        try {
            const response = await fetch('http://localhost:3000/api/chat', {
                method: 'POST',
                body: JSON.stringify({ message: value }),
            });
            const data = await response.json();
            console.log(data);
        } catch (error) {
            console.error('发送失败', error);
        } finally {
            setIsLoading(false);
        }
    }, [value]);

    return (
        <div style={styles.container}>
            <div style={styles.logoContainer}>
                <Logo size={80} />
            </div>

            <h1 style={styles.welcomeTitle}>你好呀</h1>
            <p style={styles.subtitle}>今天你想问点什么？</p>

            <div style={styles.inputSection}>
                <div style={styles.inputContainer}>
                    {selectedFiles.length > 0 && (
                        <div style={styles.fileList}>
                            {selectedFiles.map((file) => (
                                <div key={file.id} style={styles.fileCard}>
                                    <Tooltip
                                        title={
                                            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', flexDirection: 'column' }}>
                                                <div style={styles.fileName}>{file.name}</div>
                                                <div style={styles.fileType}>
                                                    {getFileTypeDisplay(file.name, file.type)} / {(file.size / 1024).toFixed(1)}KB
                                                </div>
                                            </div>
                                        }>
                                        <div style={styles.fileInfo}>
                                            <div style={styles.fileName}>{file.name}</div>
                                        </div>
                                    </Tooltip>
                                    <Button
                                        style={styles.removeButton}
                                        onClick={() => handleRemoveFile(file.id)}
                                        icon={<X size={12} />}
                                    >
                                    </Button>
                                </div>
                            ))}
                        </div>
                    )}

                    <TextArea
                        className="empty-textarea"
                        style={styles.inputField}
                        placeholder="问点什么？"
                        value={value}
                        onChange={(e) => setValue(e.target.value)}
                        rows={3}
                    />

                    <div style={styles.toolbar}>
                        <input
                            ref={fileInputRef}
                            type="file"
                            multiple
                            accept=".txt,.md,.js,.ts,.tsx,.jsx,.json,.xml,.html,.css"
                            onChange={handleFileChange}
                            style={styles.hiddenInput}
                        />
                        <ActionIcon
                            active={selectedFiles.length > 0}
                            style={styles.toolButton}
                            icon={<Paperclip size={16} />}
                            onClick={handlePaperclipClick}
                        />
                        <ActionIcon
                            active={webSearchEnabled}
                            style={styles.toolButton}
                            icon={<Globe size={16} />}
                            onClick={handleGlobeClick}
                        />
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: '0.5rem',
                            marginLeft: 'auto',
                        }}>
                            <ActionIcon
                                onClick={handleSendClick}
                                disabled={isLoading || !value}
                                loading={isLoading}
                                active={webSearchEnabled}
                                style={{
                                    ...styles.toolButton,
                                    backgroundColor: '#007bff',
                                    color: 'white',
                                }}
                                icon={<ArrowUp />}
                            />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}